import { Component, ViewEncapsulation } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormBuilder, FormGroup, Validator, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { PaginationInstance } from 'ngx-pagination';
import * as moment from 'moment';
import * as _ from 'lodash';

import { ApiRequest } from 'service/ApiRequest';
import { SignalRService } from 'service/SignalRService';
import { HOT_PRODUCT } from 'utils/index';


@Component({
    selector: 'news',
    encapsulation: ViewEncapsulation.Emulated,
    templateUrl: './News.html',
    styleUrls: []
  }
)

export class NewsComponent {

  private pagination:PaginationInstance = {
    id: 'news-list',
    itemsPerPage: 10,
    currentPage: 0,
    totalItems: 1000
  };

  categoryList = [];
  currentIndex = 0;

  newsList = [];

  productList = HOT_PRODUCT;

  signalRService: SignalRService = new SignalRService('forexHub');

  constructor(private apiRequest:ApiRequest) {

  }

  ngOnInit() {
    this.loadCategory();
    this.subscribe();
  }

  onPageChange(page) {
    console.log(page);
  }

  loadCategory() {
    this.apiRequest.getNewsMeta().then((data) => {
      this.categoryList = data;
      const eTime = moment(moment().format('YYYY-MM-DD 23:59:59')).unix();
      const sTime = moment(moment().format('YYYY-MM-DD 00:00:00')).unix();
      this.loadNews(this.categoryList[this.currentIndex].CategoryId, sTime, eTime );
    });
  }

  onChangeCategory(index) {
    this.currentIndex = index;
    const eTime = moment(moment().format('YYYY-MM-DD 23:59:59')).unix();
    const sTime = moment(moment().format('YYYY-MM-DD 00:00:00')).unix();
    this.loadNews(this.categoryList[this.currentIndex].CategoryId, sTime, eTime );
  }

  loadNews(categoryId, sTime, eTime) {
    this.apiRequest.getNewsBases(categoryId, sTime, eTime).then((data) => {
      this.newsList = data;
    });
  }

  subscribe() {
    this.signalRService.registerOn("onNewBasicProductInfoStr", (symbol, data)=> {
			const list = data.split("-");
			const close = parseFloat(list[7]);
			const time = parseInt(list[1]);

      let floating = 0;
      let percent = '-';

      if (parseFloat(list[4]) !== 0 && parseFloat(list[5]) !== 0 && parseFloat(list[5]) !== 0) {
        floating = parseFloat(list[7])- parseFloat(list[4]);
        percent = (floating / parseFloat(list[4]) * 100).toFixed(2);
      }

      const quoteBasic = {
        Symbol: list[0],
        Time: parseInt(list[1]) * 1000,
        Volume: list[2],
        YesterdayClose: parseFloat(list[3]),
        DayOpen: parseFloat(list[4]),
        DayHigh: parseFloat(list[5]),
        DayLow: parseFloat(list[6]),
        CurrentPrice: parseFloat(list[7]),
        BuyPrice: parseFloat(list[8]),
        SellPrice: parseFloat(list[9]),
        floating: floating,
        percent: percent
      };

      const index = _.findIndex(this.productList, (item) => item['Symbol'] === symbol);
      if (index > -1) {
        this.productList[index]['quote'] = quoteBasic;  
      }
		});

    const newSymbols = this.productList.map(item => item.Symbol);
		this.signalRService.getConnection().done((data: any) => {
				this.signalRService.subscribe(newSymbols.join(';'));
		}).fail((error: any) => {  
				console.log('Could not connect ' + error);  
		});
  }

  unSubscribe() {
    const symbols = this.productList.map(item => item.Symbol);
    this.signalRService.unSubscribe(symbols);
  }

   ngOnDestroy() {
    this.unSubscribe();
	}
}